package com.zero.execute.writer;

import com.zero.core.ZeroContext;
import com.zero.util.BaseUtil;
import com.zero.util.FreemarkerUtils;
import com.zero.xmodel.definition.DaoDefinition;
import com.zero.xmodel.definition.EntityDefinition;

import java.util.HashMap;
import java.util.Map;

/**
 * dao层生成器
 *
 * @author wuxi
 * @date 2020-07-28
 */
public class DaoWriter implements Writer {

    private ZeroContext context;

    public DaoWriter(ZeroContext context) {
        this.context = context;
    }

    @Override
    public void create() {
        Map<String, EntityDefinition> entityMap = this.context.getEntityMap();
        Map<String, DaoDefinition> daoMap = new HashMap<>(entityMap.size());
        for (Map.Entry<String, EntityDefinition> entry : entityMap.entrySet()) {
            //构建dao的定义对象
            DaoDefinition daoDefinition = builderDaoDefinition(entry);
            //生成dao层
            generateDao(daoMap, daoDefinition);
        }
        if (!daoMap.isEmpty()) {
            this.context.setDaoMap(daoMap);
        }
    }

    /**
     * 生成dao层
     *
     * @param daoMap        dao的容器
     * @param daoDefinition dao的定义
     */
    private void generateDao(Map<String, DaoDefinition> daoMap, DaoDefinition daoDefinition) {
        Map<String, Object> data = new HashMap<>(1);
        //使用模板
        data.put("dao", daoDefinition);
        FreemarkerUtils.getTemplate(
                this.context.getFreemarkerTemplateMap().get("daoTemplate"),
                data,
                this.context.getPackagePO().getDaoPackageName() + this.context.getSeparator() + daoDefinition.getClassName(),
                this.context.getSeparator());
        //加入容器
        daoMap.put(daoDefinition.getClassName(), daoDefinition);
    }

    /**
     * 构建一个dao的定义
     *
     * @param entry 参数
     */
    private DaoDefinition builderDaoDefinition(Map.Entry<String, EntityDefinition> entry) {
        String pojoName = entry.getKey();
        EntityDefinition entity = entry.getValue();
        DaoDefinition daoDefinition = new DaoDefinition();
        String className = pojoName.replace("PO", "Mapper");
        daoDefinition.setClassName(className);
        daoDefinition.setPojoClass(entity.getPackageName() + "." + pojoName);
        daoDefinition.setPojoName(pojoName);
        daoDefinition.setPackageName(BaseUtil.parsingPackage(this.context.getPackagePO().getDaoPackageName(),
                this.context.getSeparator()));
        return daoDefinition;
    }

}